package com.permission_demo.aop;

import com.permission_demo.annotation.Permission;
import com.permission_demo.exception.PermissionDeniedException;
import com.permission_demo.service.PermissionService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Objects;

@Aspect
@Component
public class PermissionAspect {

    @Autowired
    private PermissionService permissionService;


    // 定义切点，匹配所有带有@Permission注解的类和方法
    @Pointcut(value = "@within(com.permission_demo.annotation.Permission) || @annotation(com.permission_demo.annotation.Permission)")
    public void pointCut() {
    }

    //环绕通知
    @Around("pointCut()")
    public Object aroundPermission(ProceedingJoinPoint joinPoint) throws Throwable {
        // 1. 获取类上的权限注解
        Class<?> targetClass = joinPoint.getTarget().getClass();
        Permission classPermission = targetClass.getAnnotation(Permission.class);

        // 如果类上没有定义权限直接放行
        if (Objects.isNull(classPermission)) {
            return joinPoint.proceed();
        }

        // 2. 获取方法上的权限注解
        Method method = ((MethodSignature) joinPoint.getSignature()).getMethod();
        Permission methodPermission = method.getAnnotation(Permission.class);
        if (Objects.isNull(methodPermission)) {
            return joinPoint.proceed();
        }

        if (!permissionService.hasPermission(classPermission.code() + "$" + methodPermission.code())) {
            throw new PermissionDeniedException("没有权限访问！");
        }

        return joinPoint.proceed();
    }
}
